package com.glsc.ngateway.common.api.common.utils;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import java.util.List;

/**
 * @author pggsnap
 * @date 2020/6/1
 */
public class PageUtil {
    public static int initPageNo(Integer pageNo) {
        if (pageNo == null || pageNo < 1) {
            return 1;
        }
        return pageNo;
    }

    public static int initPageSize(Integer pageSize) {
        if (pageSize == null || pageSize < 1) {
            return 10;
        }
        return pageSize;
    }

    public static <T> Page<T> listConvertToPage(List<T> list, Pageable pageable) {
        int start = (int) pageable.getOffset();
        int end = (start + pageable.getPageSize()) > list.size() ? list.size() : (start + pageable.getPageSize());
        return new PageImpl<T>(list.subList(start, end), pageable, list.size());
    }

    public static int getStart(int pageNo, int pageSize) {
        pageNo = initPageNo(pageNo);
        pageSize = initPageSize(pageSize);
        return (pageNo - 1) * pageSize;
    }
}
